package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.pojo.Item;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ItemListener {
    @Autowired
    private RestHighLevelClient client;
    @RabbitListener(queues = "item.insert.queue")
    public void handleMessage(String msg) throws IOException {
        System.out.println("接收到消息："+msg);
//        将json转换成对象
        Item item = JSON.parseObject(msg, Item.class);
//        将数据更新到es中
        UpdateRequest request = new UpdateRequest("item_doc", item.getId().toString());
//        更新数据
        request.doc(JSON.toJSONString(item), XContentType.JSON);
        client.update(request, RequestOptions.DEFAULT);
    }
}
